import {Component, OnDestroy, OnInit, ViewEncapsulation} from '@angular/core';

import {MatTreeFlatDataSource, MatTreeFlattener} from '@angular/material/tree';
import {FlatTreeControl} from '@angular/cdk/tree';

import { Subject } from 'rxjs';

import { baseAnimations } from '@base/animations';
import { BaseUtils } from '@base/utils';

import {SettingUserService} from './user.service';
import { takeUntil } from 'rxjs/internal/operators';
import {User} from './user.module';
import {FormBuilder, FormGroup} from '@angular/forms';
import {Location} from '@angular/common';
import {MatSnackBar} from '@angular/material/snack-bar';



/**
 * Food data with nested structure.
 * Each node has a name and an optiona list of children.
 */
interface FoodNode {
    name: string;
    children?: FoodNode[];
}

const TREE_DATA: FoodNode[] = [
    {
        name: 'Fruit',
        children: [
            {name: 'Apple'},
            {name: 'Banana'},
            {name: 'Fruit loops'},
        ]
    }, {
        name: 'Vegetables',
        children: [
            {
                name: 'Green',
                children: [
                    {name: 'Broccoli'},
                    {name: 'Brussel sprouts'},
                ]
            }, {
                name: 'Orange',
                children: [
                    {name: 'Pumpkins'},
                    {name: 'Carrots'},
                ]
            },
        ]
    },
];

/** Flat node with expandable and level information */
interface ExampleFlatNode {
    expandable: boolean;
    name: string;
    level: number;
}

@Component({
    selector     : 'permissions-user',
    templateUrl  : './user.component.html',
    styleUrls    : ['./user.component.scss'],
    animations   : baseAnimations,
    encapsulation: ViewEncapsulation.None,
})
export class SettingUserComponent implements OnInit, OnDestroy
{



    displayedColumns: string[] = ['id', 'name', 'age'];

    user: User;
    pageType: string;
    userForm: FormGroup;

    selected:any;

    // Private
    private _unsubscribeAll: Subject<any>;


    treeControl: FlatTreeControl<ExampleFlatNode>;
    treeFlattener: MatTreeFlattener<FoodNode, ExampleFlatNode>;
    dataSource: MatTreeFlatDataSource<FoodNode, ExampleFlatNode>;


    /**
     * Constructor
     *
     * @param _settingUserService
     * @param {FormBuilder} _formBuilder
     * @param {Location} _location
     * @param {MatSnackBar} _matSnackBar
     */
    constructor(
        private _settingUserService: SettingUserService,
        private _formBuilder: FormBuilder,
        private _location: Location,
        private _matSnackBar: MatSnackBar
    )
    {
        // Set the private defaults
        this._unsubscribeAll = new Subject();

        this.treeControl = new FlatTreeControl<ExampleFlatNode>(
            node => node.level, node => node.expandable);

        this.treeFlattener = new MatTreeFlattener(
            ((node: FoodNode, level: number) => {
                return {
                    expandable: !!node.children && node.children.length > 0,
                    name: node.name,
                    level: level,
                };
            }), node => node.level, node => node.expandable, node => node.children);

        this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
        this.dataSource.data = TREE_DATA;
        // Set the default
        this.user = new User();

        console.log(this.dataSource.data)

    }

    hasChild = (_: number, node: ExampleFlatNode) => node.expandable;


    /**
     * On init
     */
    ngOnInit(): void
    {

        // Subscribe to update user on changes
        this._settingUserService.onUserChanged
            .pipe(takeUntil(this._unsubscribeAll))
            .subscribe(user => {

                if ( user )
                {
                    this.user = new User(user);
                    this.pageType = 'edit';
                }
                else
                {
                    this.pageType = 'new';
                    this.user = new User();
                }

                this.userForm = this.createUserForm();
            });
    }

    /**
     * On destroy
     */
    ngOnDestroy(): void
    {
        // Unsubscribe from all subscriptions
        this._unsubscribeAll.next();
        this._unsubscribeAll.complete();
    }

    // -----------------------------------------------------------------------------------------------------
    // @ Public methods
    // -----------------------------------------------------------------------------------------------------


    /**
     * Create product form
     *
     * @returns {FormGroup}
     */
    createUserForm(): FormGroup
    {
        return this._formBuilder.group({
            id              : [this.user.id],
            name            : [this.user.name],
            username     : [this.user.username],
            password      : [this.user.password],
            sex            : [this.user.sex],
            pinyin          : [this.user.pinyin],
            email    : [this.user.email],
            priceTaxIncl    : [this.user.priceTaxIncl],
            taxRate         : [this.user.taxRate],
            comparedPrice   : [this.user.comparedPrice],
            quantity        : [this.user.quantity],
            sku             : [this.user.sku],
            width           : [this.user.width],
            height          : [this.user.height],
            depth           : [this.user.depth],
            weight          : [this.user.weight],
            extraShippingFee: [this.user.extraShippingFee],
            active          : [this.user.active]
        });
    }

    /**
     * Save product
     */
    saveUser(): void
    {
        const data = this.userForm.getRawValue();
        data.handle = BaseUtils.handleize(data.name);

        this._settingUserService.saveUser(data)
            .then(() => {

                // Trigger the subscription with new data
                this._settingUserService.onUserChanged.next(data);

                // Show the success message
                this._matSnackBar.open('Product saved', 'OK', {
                    verticalPosition: 'top',
                    duration        : 2000
                });
            });
    }

    /**
     * Add product
     */
    addProduct(): void
    {
        const data = this.userForm.getRawValue();
        data.handle = BaseUtils.handleize(data.name);

        this._settingUserService.addUser(data)
            .then(() => {

                // Trigger the subscription with new data
                this._settingUserService.onUserChanged.next(data);

                // Show the success message
                this._matSnackBar.open('User added', 'OK', {
                    verticalPosition: 'top',
                    duration        : 2000
                });

                // Change the location with new one
                this._location.go('apps/e-commerce/products/' + this.user.id + '/' + this.user.handle);
            });
    }






}
